package com.bicon.botu.mall.component.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bicon.botu.mall.component.common.BannerConstants;
import com.bicon.botu.mall.component.processor.rpc.service.GoodsInvoker;
import com.bicon.botu.mall.component.service.IBannerService;
import com.bicon.botu.mall.component.dto.BannerDto;
import com.bicon.botu.mall.component.entity.Banner;
import com.bicon.botu.mall.component.mapper.BannerMapper;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.core.base.common.utils.JsonUtil;
import com.bicon.botu.core.base.repository.redis.RedisHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 轮播图 服务实现类
 *
 * @author 张凡
 * @date 2017/7/19 下午 14:49
 */
@Service
@Transactional
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner> implements IBannerService {
    @Autowired
    RedisHandler redisHandler;
    private static final String redisKey = BannerConstants.REDIS_KEY;

    @Autowired
    GoodsInvoker goodsInvoker;

    /**
     * 增加轮播图
     *
     * @param bannerModular  轮播图模块
     * @param bannerPosition 轮播图位置
     * @param banners        轮播图对象集合
     * @return
     */
    @Override
    public boolean insert(Integer bannerModular, Integer bannerPosition, List<Banner> banners) {
        boolean result;
        //设置sort为当前总条数
        Integer rows = new Banner().selectCount(new EntityWrapper<Banner>()
                .eq("logic_delete", BannerConstants.DEL_LOGIC_NORMAL)
                .eq("banner_position", bannerPosition)
                .eq("banner_modular", bannerModular));
        for (Banner banner : banners) {
            //设置序号为最大值
            banner.setBannerSort(++rows);
            banner.preInsert();
            result = banner.insert();
            if (!result) {
                return false;
            }
        }
        //初始化
        this.initBannerToRedis(bannerModular, bannerPosition);
        return true;
    }

    /**
     * 删除轮播图
     *
     * @param bannerModular  轮播图模块
     * @param bannerPosition 轮播图位置
     * @param idJson         轮播图Id集合
     * @return
     */
    @Override
    public BaseResult delete(Integer bannerModular, Integer bannerPosition, String idJson) {
        ArrayList<String> idList = JsonUtil.fromJson(idJson, ArrayList.class);
        Integer num = new Banner().selectCount(new EntityWrapper<Banner>().eq("logic_delete", BannerConstants.DEL_LOGIC_NORMAL)
                .eq("banner_position", bannerPosition)
                .eq("banner_modular", bannerModular));
        if (num == 1) {
            return new BaseResult(BannerConstants.RESPONSE_CODE_605, BannerConstants.RESPONSE_MESSAGE_605);
        }
        boolean result;
        for (int i = 0; i < idList.size(); i++) {
            //判断轮播图是否关闭，关闭的才可以删除
            Banner banner = new Banner().selectOne(new EntityWrapper<Banner>().eq("id", idList.get(i))
                    .eq("logic_delete", BannerConstants.DEL_LOGIC_NORMAL)
                    .eq("banner_position", bannerPosition)
                    .eq("banner_modular", bannerModular)
                    .eq("banner_flag", BannerConstants.BANNER_OFF));
            if (null == banner) {
                return new BaseResult(BannerConstants.RESPONSE_CODE_602, BannerConstants.RESPONSE_MESSAGE_602);
            }
            int sort = banner.getBannerSort();
            banner.setLogicDelete(BannerConstants.DEL_LOGIC_DELETE);
            banner.setBannerSort(0);
            banner.preUpdate();
            result = banner.updateById();
            //调rpc
            goodsInvoker.updateProductState(banner.getGoodsIds(), "0");
            if (!result) {
                return new BaseResult(BannerConstants.RESPONSE_CODE_500, BannerConstants.RESPONSE_MESSAGE_500);
            }
            if (num != sort) {
                List<Banner> bannerList = new Banner().selectList(new EntityWrapper<Banner>()
                        .eq("banner_position", bannerPosition)
                        .eq("banner_modular", bannerModular)
                        .eq("logic_delete", BannerConstants.DEL_LOGIC_NORMAL)
                        .gt("banner_sort", sort));
                List<Banner> banners = new ArrayList<Banner>();
                for (Banner banner1 : bannerList) {
                    banner1.setBannerSort(banner1.getBannerSort() - 1);
                    banner1.preUpdate();
                    banners.add(banner1);
                }
                result = updateBatchById(banners);
                if (!result) {
                    return new BaseResult(BannerConstants.RESPONSE_CODE_500, BannerConstants.RESPONSE_MESSAGE_500);
                }

            }
        }
        //修改后重新初始化
        this.initBannerToRedis(bannerModular, bannerPosition);
        return new BaseResult(BannerConstants.RESPONSE_CODE_200, BannerConstants.RESPONSE_MESSAGE_200);
    }

    /**
     * 修改轮播图
     *
     * @param bannerModular  轮播图模块
     * @param bannerPosition 轮播图位置
     * @param banners        轮播图对象集合
     * @return
     */
    @Override
    public BaseResult update(Integer bannerModular, Integer bannerPosition, List<Banner> banners) {
        boolean result;
        for (Banner banner : banners) {
            //根据Id判断是否存在
            Banner banner1 = new Banner().selectOne(new EntityWrapper<Banner>().eq("id", banner.getId())
                    .eq("logic_delete", BannerConstants.DEL_LOGIC_NORMAL));
            if (null == banner1) {
                return new BaseResult(BannerConstants.RESPONSE_CODE_404, BannerConstants.RESPONSE_MESSAGE_404);
            }
            if (banner1.getGoodsIds() != null) {
                goodsInvoker.updateProductState(banner1.getGoodsIds(), "0");
            }
            if (banner.getGoodsIds() != null) {
                goodsInvoker.updateProductState(banner.getGoodsIds(), "1");
            }

            //直接修改轮播图表
            result = banner.updateById();
            if (!result) {
                return new BaseResult(BannerConstants.RESPONSE_CODE_500, BannerConstants.RESPONSE_MESSAGE_500);
            }
        }
        //修改后重新初始化
        this.initBannerToRedis(bannerModular, bannerPosition);
        return new BaseResult(BannerConstants.RESPONSE_CODE_200, BannerConstants.RESPONSE_MESSAGE_200);
    }

    /**
     * 初始化轮播图到redis
     *
     * @param bannerModular  轮播图模块
     * @param bannerPosition 轮播图位置
     * @return
     */
    @Override
    public BaseResult initBannerToRedis(Integer bannerModular, Integer bannerPosition) {
        //查询出所有正常的轮播图
        List<Banner> banners = new Banner().selectList(new EntityWrapper<Banner>()
                .eq("banner_position", bannerPosition).eq("banner_modular", bannerModular).eq("banner_flag", BannerConstants.BANNER_ON)
                .eq("logic_delete", BannerConstants.DEL_LOGIC_NORMAL).orderBy("banner_sort", false));
        List<BannerDto> bannerDtoList = new ArrayList<>();
        for (Banner banner : banners) {
            BannerDto bannerDto = new BannerDto();
            bannerDto.setId(banner.getId());
            if (banner.getBannerContext() != null) {
                bannerDto.setBannerContext(banner.getBannerContext());
            }
            if (banner.getBannerFlag() != null) {
                bannerDto.setBannerFlag(banner.getBannerFlag());
            }
            if (banner.getBannerImage() != null) {
                bannerDto.setBannerImage(banner.getBannerImage());
            }
            if (banner.getBannerModular() != null) {
                bannerDto.setBannerModular(banner.getBannerModular());
            }
            if (banner.getBannerName() != null) {
                bannerDto.setBannerName(banner.getBannerName());
            }
            if (banner.getBannerPosition() != null) {
                bannerDto.setBannerPosition(banner.getBannerPosition());
            }
            if (banner.getBannerSort() != null) {
                bannerDto.setBannerSort(banner.getBannerSort());
            }
            if (banner.getBannerUrl() != null) {
                bannerDto.setBannerUrl(banner.getBannerUrl());
            }
            if (banner.getGoodsIds() != null) {
                bannerDto.setGoodsIds(banner.getGoodsIds());
            }
            if (banner.getResponseType() != null) {
                bannerDto.setResponseType(banner.getResponseType());
            }
            bannerDtoList.add(bannerDto);
        }
        //保存到redis上
        if (bannerModular == BannerConstants.MALL) {
            //清除缓存
            redisHandler.getGlobalRedisTemplate().remove(redisKey, ":" + BannerConstants.MALL_MODULAR);
            //将轮播图存到redis
            redisHandler.getGlobalRedisTemplate().cacheHash(redisKey, ":" + BannerConstants.MALL_MODULAR,
                    bannerPosition + "", JsonUtil.toJson(bannerDtoList));
        } else if (bannerModular == BannerConstants.HOSPITAL) {
            //清除缓存
            redisHandler.getGlobalRedisTemplate().remove(redisKey, ":" + BannerConstants.HOSPITAL_MODULAR);
            //将轮播图存到redis
            redisHandler.getGlobalRedisTemplate().cacheHash(redisKey, ":" + BannerConstants.HOSPITAL_MODULAR,
                    bannerPosition + "", JsonUtil.toJson(bannerDtoList));
        } else if (bannerModular == BannerConstants.ENCOURAGE) {
            //清除缓存
            redisHandler.getGlobalRedisTemplate().remove(redisKey, ":" + BannerConstants.ENCOURAGE_MODULAR);
            //将轮播图存到redis
            redisHandler.getGlobalRedisTemplate().cacheHash(redisKey, ":" + BannerConstants.ENCOURAGE_MODULAR,
                    bannerPosition + "", JsonUtil.toJson(bannerDtoList));
        }
        return new BaseResult(BannerConstants.RESPONSE_CODE_200, BannerConstants.RESPONSE_MESSAGE_200);
    }

    /**
     * 获取轮播图详情
     *
     * @param bannerModular  轮播图模块
     * @param bannerPosition 轮播图位置
     * @return
     */
    @Override
    public List<BannerDto> getBannerDetailFromRedis(Integer bannerModular, Integer bannerPosition) {
        //从redis上获取轮播图详情
        List<BannerDto> bannerDtos = new ArrayList<>();
        if (bannerModular == BannerConstants.MALL) {
            String bannersJson = redisHandler.getGlobalRedisTemplate().getHash(redisKey, ":" + BannerConstants.MALL_MODULAR, bannerPosition + "");
            bannerDtos = JsonUtil.fromJson(bannersJson, ArrayList.class);
        } else if (bannerModular == BannerConstants.HOSPITAL) {
            String bannersJson = redisHandler.getGlobalRedisTemplate().getHash(redisKey, ":" + BannerConstants.HOSPITAL_MODULAR, bannerPosition + "");
            bannerDtos = JsonUtil.fromJson(bannersJson, ArrayList.class);
        } else if (bannerModular == BannerConstants.ENCOURAGE) {
            String bannersJson = redisHandler.getGlobalRedisTemplate().getHash(redisKey, ":" + BannerConstants.ENCOURAGE_MODULAR, bannerPosition + "");
            bannerDtos = JsonUtil.fromJson(bannersJson, ArrayList.class);
        }
        return bannerDtos;
    }

    /**
     * 修改排序
     *
     * @param bannerModular  轮播图模块
     * @param bannerPosition 轮播图位置
     * @param bannerId       轮播图id
     * @param operation      向上还是向下
     * @return
     */
    @Override
    public BaseResult bannerSort(Integer bannerModular, Integer bannerPosition, Integer bannerId, String operation) {
        //判断轮播图id是否存在
        Banner banner = new Banner().selectOne(new EntityWrapper<Banner>().eq("id", bannerId)
                .eq("logic_delete", BannerConstants.DEL_LOGIC_NORMAL));
        if (null == banner) {
            return new BaseResult(BannerConstants.RESPONSE_CODE_404, BannerConstants.RESPONSE_MESSAGE_404);
        }
        if (BannerConstants.SORT_UP.equals(operation)) {
            Banner upBanner = new Banner().selectOne(new EntityWrapper<Banner>().eq("banner_position", bannerPosition).
                    eq("banner_modular", bannerModular).eq("logic_delete", BannerConstants.DEL_LOGIC_NORMAL)
                    .eq("banner_sort", banner.getBannerSort() + 1));
            upBanner.setBannerSort(banner.getBannerSort());
            upBanner.preUpdate();
            boolean result = upBanner.updateById();
            if (!result) {
                return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
            }
            banner.setBannerSort(banner.getBannerSort() + 1);
            banner.preUpdate();
            result = banner.updateById();
            if (!result) {
                return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
            }
        }
        if (BannerConstants.SORT_DOWN.equals(operation)) {
            Banner downBanner = new Banner().selectOne(new EntityWrapper<Banner>().eq("banner_position", bannerPosition).
                    eq("banner_modular", bannerModular).eq("logic_delete", BannerConstants.DEL_LOGIC_NORMAL).
                    eq("banner_sort", banner.getBannerSort() - 1));
            downBanner.setBannerSort(banner.getBannerSort());
            downBanner.preUpdate();
            boolean result = downBanner.updateById();
            if (!result) {
                return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
            }
            banner.setBannerSort(banner.getBannerSort() - 1);
            banner.preUpdate();
            result = banner.updateById();
            if (!result) {
                return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
            }
        }
        //初始化到redis上
        this.initBannerToRedis(bannerModular, bannerPosition);
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }


}
